package com.stars.easyms.gateway.filter;

import com.stars.easyms.base.constant.HttpHeaderConstants;
import com.stars.easyms.gateway.constant.EasyMsGatewayConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Map;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.addOriginalRequestUrl;

/**
 * <p>className: EasyMsClearRequestTraceFilter</p>
 * <p>description: 清除缓存</p>
 *
 * @author guoguifang
 * @version 1.6.1
 * @date 2020/8/20 18:32
 */
@Slf4j
public class EasyMsDebugFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 如果开启了debug模式则把debug的url直接跳过权限校验
        if (exchange.getAttribute(EasyMsGatewayConstants.DEBUG) != null) {
            exchange.getAttributes().remove(EasyMsGatewayConstants.DEBUG);
            ServerHttpRequest req = exchange.getRequest();
            addOriginalRequestUrl(exchange, req.getURI());
            String path = req.getURI().getRawPath();
            String newPath = null;
            for (Map.Entry<String, String> entry : HttpHeaderConstants.EASY_MS_URL_REPLACE_MAP.entrySet()) {
                String temp = path.replaceAll(entry.getKey(), entry.getValue());
                if (!temp.equals(path)) {
                    newPath = temp;
                    break;
                }
            }
            if (newPath != null) {
                ServerHttpRequest request = req.mutate().path(newPath).build();
                exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, request.getURI());
                return chain.filter(exchange.mutate().request(request).build());
            }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1000;
    }

}
